package br.com.emmis.tercons;

import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.android.vending.billing.IabHelper;
import com.android.vending.billing.IabResult;
import com.android.vending.billing.Inventory;
import com.android.vending.billing.Purchase;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.tjeannin.apprate.AppRate;

import br.com.emmis.tercons.constants.Constants;
import br.com.emmis.tercons.model.Config;
import br.com.emmis.tercons.model.Intention;
import br.com.emmis.tercons.util.AmemUpdateUtil;

import static br.com.emmis.tercons.SendingIntentionsFragment.OnFragmentInteractionListener;

public class MainActivity extends ActionBarActivity implements MenuFragment.OnMenuFragmentInteractionListener, RezarFragment.OnRezarFragmentInteractionListener , FinishFragment.OnFragmentInteractionListener, LoadingIntentionsFragment.OnFragmentInteractionListener, IntentionFragment.OnFragmentInteractionListener, MyIntentionFragment.OnFragmentInteractionListener, OnFragmentInteractionListener{

    // Debug tag, for logging
    private static final String TAG = "MainActivity";

    // Fragments
    private MenuFragment mMenuFragment;
    private RezarFragment mRezarFragment;
    private SettingsFragment mSettingsFragment;
    private FinishFragment mFinishedFragment;
    private LoadingIntentionsFragment mLoadingIntentionsFragment;
    private IntentionFragment mIntentionFragment;
    private MyIntentionFragment mMyIntentionFragment;
    private SendingIntentionsFragment mSendingIntentionsFragment;
    private int mNextCount;
    private static boolean mRemoverAds = false;
	private static boolean mDonator = false;

    private AlertDialog alerta;
    private InterstitialAd mInterstitial;

    private IabHelper mHelper;
    static final String SKU_REMOVE_ADS = "remove_adds";
	static final String SKU_DONATOR_SUB = "donation_subscription";

    static final int RC_REQUEST = 10101;
    private String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn+sAliT12uGmZRWtWml0aU9dCcvgIqPaUX2yQcNqT9ZZhJEoY+sWhdGqZoNPHzvULfOJwVYStXJThbpB/XkzJuhYtRRGaGSF6/5TnOec2Fkh5LpAg09nVJ5oxmXG20o7xu1xgDyN9jUmg3ZNyOpdaS9P7tb/ztvbvl1CGiXSsjNxidh6f76AQnUFWamUukhY9xcm5oWwd+Ph+Vv8Q6Syu/6W4IfOlkyFI6aQjx3XIzHfMjq0U/13gchLOm/MM48lY8p4Rxy+S84u6eEDRC68x9cYACUuofLUixjSpde5zoNxjKvKF1V9k4BsjEE2NmYEWUCOq5fyJV8hZ7S5bVZYBQIDAQAB";
    private String mPayload = "EMMIS-X";

    private EasyTracker mEasyTracker;
    private Config mConfig;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mConfig = Config.getInstance(getApplicationContext());

        mEasyTracker = EasyTracker.getInstance(this);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);

        mRemoverAds  = mConfig.ismRemoveAds();
		mDonator = mConfig.ismDonor();

        // Create the helper, passing it our context and the public key to verify signatures with
        Log.d(TAG, "Creating IAB helper.");
        mHelper = new IabHelper(this, base64EncodedPublicKey);

        // Start setup. This is asynchronous and the specified listener
        // will be called once setup completes.
        Log.d(TAG, "Starting setup.");

        mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
            public void onIabSetupFinished(IabResult result) {
                Log.d(TAG, "Setup finished.");

                if (!result.isSuccess()) {
                    // Oh noes, there was a problem.
                    Log.e(TAG, "Problem setting up in-app billing: " + result);
                    return;
                }

                // Have we been disposed of in the meantime? If so, quit.
                if (mHelper == null) return;

                // IAB is fully set up. Now, let's get an inventory of stuff we own.
                Log.d(TAG, "Setup successful. Querying inventory.");
                mHelper.queryInventoryAsync(mGotInventoryListener);
            }
        });

        // Criar o anúncio intersticial.
        mInterstitial = new InterstitialAd(this);
        mInterstitial.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
        // Criar a solicitação de anúncio.
        final AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).addTestDevice("5A9C3E1F678D893049DD767D587A4446").build();
        // Começar a carregar o anúncio intersticial.

        if(!mRemoverAds && !mDonator) {
            mInterstitial.loadAd(adRequest);
            mInterstitial.setAdListener(new AdListener() {
                @Override
                public void onAdClosed() {
                    mInterstitial.loadAd(adRequest);
                    super.onAdClosed();
                }
            });
        }

        mMenuFragment = MenuFragment.newInstance("","");
        mMenuFragment.onAttach(this);

        mRezarFragment = RezarFragment.newInstance();
        mRezarFragment.onAttach(this);

        mSettingsFragment = SettingsFragment.newInstance();
        mSettingsFragment.onAttach(this);

        mFinishedFragment = FinishFragment.newInstance("","");
        mFinishedFragment.onAttach(this);

        mLoadingIntentionsFragment = mLoadingIntentionsFragment.newInstance();
        mLoadingIntentionsFragment.onAttach(this);

        mNextCount=0;

        getFragmentManager().beginTransaction()
                .add(R.id.container, mMenuFragment)
                .commit();

        try {

            AlertDialog.Builder builder = new AlertDialog.Builder(this)
                    .setMessage(R.string.app_rate_message)
                    .setPositiveButton(R.string.app_rate_positive, null)
                    .setNegativeButton(R.string.app_rate_neutral, null)
                    .setNeutralButton(R.string.app_rate_negative, null);

            new AppRate(this)
                    .setMinDaysUntilPrompt(2)
                    .setMinLaunchesUntilPrompt(5)
                    .setShowIfAppHasCrashed(false)
                    .setCustomDialog(builder)
                    .init();
        } catch (Exception ex) {
            mEasyTracker.send(MapBuilder
                    .createEvent("app_exception",     // Event category (required)
                            "catch",  // Event action (required)
                            "app_rate",   // Event label
                            null)            // Event value
                    .build());
        }

        Intent intent = getIntent();
        if(Constants.ACTION_INTENTION_NOTIFICATION.equals(intent.getAction())){
            mIntentionFragment = IntentionFragment.newInstance(intent.getIntExtra(Constants.EXTRA_INTENTION_ID, 0), intent.getStringExtra(Constants.EXTRA_INTENTION_NAME), intent.getStringExtra(Constants.EXTRA_INTENTION_PRAY), intent.getIntExtra(Constants.EXTRA_INTENTION_AMEM,-1), 0);
            switchToFragment(mIntentionFragment);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        mEasyTracker.activityStop(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mEasyTracker.activityStart(this);
    }

    public boolean onSupportNavigateUp () {
        if (getFragmentManager().getBackStackEntryCount() > 0) {
            getFragmentManager().popBackStack();
            return true;
        } else {
            return super.onSupportNavigateUp ();
        }
    }

    @Override
    public void onBackPressed()
    {
        if (getFragmentManager().getBackStackEntryCount() > 0) {
            getFragmentManager().popBackStack();
        } else {
            super.onBackPressed();
        }
    }

    // Switch UI to the given fragment
    void switchToFragment(Fragment newFrag) {
        getFragmentManager().beginTransaction().replace(R.id.container, newFrag).addToBackStack(null)
                .commit();
    }

    public void displayInterstitial() {
        if (!mRemoverAds && !mDonator && mInterstitial.isLoaded()) {
            mInterstitial.show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_activity_actions, menu);
        MenuItem item = menu.findItem(R.id.action_remove_ads);
        if(mRemoverAds || mDonator) {
            item.setVisible(false);
        }
		
		MenuItem item2 = menu.findItem(R.id.action_donator);
        if(mDonator) {
            item2.setVisible(false);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            mEasyTracker.send(MapBuilder
                    .createEvent("ui_action",     // Event category (required)
                            "menu_option_press",  // Event action (required)
                            "settings",   // Event label
                            null)            // Event value
                    .build());
            switchToFragment(mSettingsFragment);
        } else if(id == R.id.action_contato || id == R.id.action_report) {
            mEasyTracker.send(MapBuilder
                    .createEvent("ui_action",     // Event category (required)
                            "menu_option_press",  // Event action (required)
                            "contact_report",   // Event label
                            null)            // Event value
                    .build());
            final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
            emailIntent.setType("plain/text");
            emailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[] { "vanerjm@gmail.com" });
            startActivity(Intent.createChooser(emailIntent,
                    getString(R.string.action_contact)));
        } else if (id == R.id.action_remove_ads) {
            mEasyTracker.send(MapBuilder
                    .createEvent("ui_action",     // Event category (required)
                            "menu_option_press",  // Event action (required)
                            "remove_ads",   // Event label
                            null)            // Event value
                    .build());
            removeAdsClicked();
        } else if (id == R.id.action_donator) {
            mEasyTracker.send(MapBuilder
                    .createEvent("ui_action",     // Event category (required)
                            "menu_option_press",  // Event action (required)
                            "donor",   // Event label
                            null)            // Event value
                    .build());
            donationClicked();
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onRezarClicked() {
        mEasyTracker.send(MapBuilder
                .createEvent("ui_action",     // Event category (required)
                        "button_press",  // Event action (required)
                        "pray",   // Event label
                        null)            // Event value
                .build());
        displayInterstitial();
        switchToFragment(mRezarFragment);
    }

    @Override
    public void onIntencoesClicked() {
        mEasyTracker.send(MapBuilder
                .createEvent("ui_action",     // Event category (required)
                        "button_press",  // Event action (required)
                        "intentions",   // Event label
                        null)            // Event value
                .build());
        switchToFragment(mLoadingIntentionsFragment);
    }

    @Override
    public void onPrayFinished() {
        mEasyTracker.send(MapBuilder
                .createEvent("life_cycle",     // Event category (required)
                        "finish",  // Event action (required)
                        "pray",   // Event label
                        null)            // Event value
                .build());

        FragmentManager fm = getFragmentManager();
        for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
            fm.popBackStack();
        }
        switchToFragment(mFinishedFragment);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    @Override
    public void onLoadingOk(Intention intention, int position) {
        mEasyTracker.send(MapBuilder
                .createEvent("life_cycle",     // Event category (required)
                        "loading",  // Event action (required)
                        "intentions",   // Event label
                        1L)            // Event value
                .build());

        mIntentionFragment = IntentionFragment.newInstance(intention.getmId(), intention.getmName(), intention.getmPrece(), intention.getmAmem(), position);

        FragmentManager fm = getFragmentManager();
        for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
            fm.popBackStack();
        }

        if(!mDonator && !mRemoverAds) {
            findViewById(R.id.adFragment).setVisibility(View.GONE);
            Handler animFinish = new Handler();
            animFinish.postDelayed(new Runnable() {
                @Override
                public void run() {
                    findViewById(R.id.adFragment).setVisibility(View.VISIBLE);
                }
            }, 2000);
        }

        switchToFragment(mIntentionFragment);

        if(mNextCount >= 3) {
            mNextCount = 0;
            displayInterstitial();
        }
    }

    @Override
    public void onLoadingError() {
        mEasyTracker.send(MapBuilder
                .createEvent("life_cycle",     // Event category (required)
                        "loading",  // Event action (required)
                        "intentions",   // Event label
                        0L)            // Event value
                .build());

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.loading_intention_error_title);
        builder.setMessage(R.string.loading_intention_error);
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int j) {
                FragmentManager fm = getFragmentManager();
                for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
                    fm.popBackStack();
                }
            }
        });
        alerta = builder.create();
        alerta.show();
    }

    @Override
    public void onMyIntentionButtonClicked() {
        mEasyTracker.send(MapBuilder
                .createEvent("ui_action",     // Event category (required)
                        "button_press",  // Event action (required)
                        "my_intentions",   // Event label
                        null)            // Event value
                .build());

        mMyIntentionFragment = MyIntentionFragment.newInstance();

        FragmentManager fm = getFragmentManager();
        for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
            fm.popBackStack();
        }
        switchToFragment(mMyIntentionFragment);
        displayInterstitial();
    }

    @Override
    public void onAmemButtonClicked(int intentionID) {
        mEasyTracker.send(MapBuilder
                .createEvent("ui_action",     // Event category (required)
                        "button_press",  // Event action (required)
                        "amen",   // Event label
                        null)            // Event value
                .build());
        AmemUpdateUtil auu = new AmemUpdateUtil(getApplicationContext());
        auu.execute(""+intentionID);
    }

    @Override
    public void onNextIntentionButtonClicked(int nextId) {
        mEasyTracker.send(MapBuilder
                .createEvent("ui_action",     // Event category (required)
                        "button_press",  // Event action (required)
                        "next_intentions",   // Event label
                        null)            // Event value
                .build());
        FragmentManager fm = getFragmentManager();
        for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
            fm.popBackStack();
        }
        mLoadingIntentionsFragment.setPrayPosition(nextId);
        mNextCount++;

        if(!mDonator && !mRemoverAds) {
            findViewById(R.id.adFragment).setVisibility(View.GONE);
            Handler animFinish = new Handler();
            animFinish.postDelayed(new Runnable() {
                @Override
                public void run() {
                    findViewById(R.id.adFragment).setVisibility(View.VISIBLE);
                }
            }, 2000);
        }

        switchToFragment(mLoadingIntentionsFragment);
    }

    @Override
    public void onIntentionSent(String name, String city, String prece) {

        FragmentManager fm = getFragmentManager();
        for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
            fm.popBackStack();
        }

        if(name != null && name.length() > 3 && prece != null && prece.length() > 5) {
            mSendingIntentionsFragment = SendingIntentionsFragment.newInstance(name, city, prece);
            switchToFragment(mSendingIntentionsFragment);
        }
    }

    @Override
    public void onSendingOk() {
        mEasyTracker.send(MapBuilder
                .createEvent("life_cycle",     // Event category (required)
                        "sending",  // Event action (required)
                        "intentions",   // Event label
                        1L)            // Event value
                .build());
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.sending_intention_ok_title);
        builder.setMessage(R.string.sending_intention_ok);
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int j) {
                FragmentManager fm = getFragmentManager();
                for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
                    fm.popBackStack();
                }
            }
        });
        alerta = builder.create();
        alerta.show();

    }

    @Override
    public void onSendingError() {
        mEasyTracker.send(MapBuilder
                .createEvent("life_cycle",     // Event category (required)
                        "sending",  // Event action (required)
                        "intentions",   // Event label
                        0L)            // Event value
                .build());
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.sending_intention_error_title);
        builder.setMessage(R.string.sending_intention_error);
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int j) {
                FragmentManager fm = getFragmentManager();
                for(int i = 0; i < fm.getBackStackEntryCount(); ++i) {
                    fm.popBackStack();
                }
            }
        });
        alerta = builder.create();
        alerta.show();
    }

    // Listener that's called when we finish querying the items and subscriptions we own
    IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() {
        public void onQueryInventoryFinished(IabResult result, Inventory inventory) {
            Log.d(TAG, "Query inventory finished.");

            // Have we been disposed of in the meantime? If so, quit.
            if (mHelper == null) return;

            // Is it a failure?
            if (result.isFailure()) {
                Log.e(TAG, "Failed to query inventory: " + result);
                return;
            }

            Log.d(TAG, "Query inventory was successful.");

            Purchase removeAds = inventory.getPurchase(SKU_REMOVE_ADS);
            mRemoverAds = (removeAds != null && verifyDeveloperPayload(removeAds));
            
			// If donator, remove ads.
            Purchase donator = inventory.getPurchase(SKU_DONATOR_SUB);
            mDonator = (donator != null &&
                    verifyDeveloperPayload(donator));
					
			if(mRemoverAds || mDonator) {
                findViewById(R.id.adFragment).setVisibility(View.GONE);
                invalidateOptionsMenu();
            }

            mConfig.setmDonor(mDonator);
            mConfig.setmRemoveAds(mRemoverAds);
        }
    };

    /** Verifies the developer payload of a purchase. */
    boolean verifyDeveloperPayload(Purchase p) {
        String payload = p.getDeveloperPayload();
        return mPayload.equals(payload);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (mHelper == null) return;

        if (!mHelper.handleActivityResult(requestCode, resultCode, data)) {
            super.onActivityResult(requestCode, resultCode, data);
        }
        else {
            Log.d(TAG, "onActivityResult handled by IABUtil.");
        }
    }

    public void removeAdsClicked() {
        mHelper.launchPurchaseFlow(this, SKU_REMOVE_ADS, RC_REQUEST,
                mPurchaseFinishedListener, mPayload);
    }
	
	public void donationClicked() {
        if (!mHelper.subscriptionsSupported()) {
            Log.e(TAG, "Subscriptions not supported on your device yet. Sorry!");
            return;
        }
        mHelper.launchPurchaseFlow(this,
                SKU_DONATOR_SUB, IabHelper.ITEM_TYPE_SUBS,
                RC_REQUEST, mPurchaseFinishedListener, mPayload);
    }

    // Callback for when a purchase is finished
    IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() {
        public void onIabPurchaseFinished(IabResult result, Purchase purchase) {
            Log.d(TAG, "Purchase finished: " + result + ", purchase: " + purchase);

            // if we were disposed of in the meantime, quit.
            if (mHelper == null) return;

            if (result.isFailure()) {
                Log.e(TAG,"Error purchasing: " + result);
                return;
            }
            if (!verifyDeveloperPayload(purchase)) {
                Log.e(TAG,"Error purchasing. Authenticity verification failed.");
                return;
            }

            Log.d(TAG, "Purchase successful.");

            if (purchase.getSku().equals(SKU_REMOVE_ADS)) {

                mRemoverAds = true;
                mConfig.setmRemoveAds(mRemoverAds);
                findViewById(R.id.adFragment).setVisibility(View.GONE);

                // May return null if EasyTracker has not yet been initialized with a
                // property ID.
                EasyTracker easyTracker = EasyTracker.getInstance(getApplicationContext());
                easyTracker.send(MapBuilder
                                .createItem(purchase.getToken(),               // (String) Transaction ID
                                        purchase.getItemType(),      // (String) Product name
                                        purchase.getSku(),                  // (String) Product SKU
                                        "Remove Ads",        // (String) Product category
                                        5.00d,                    // (Double) Product price
                                        1L,                       // (Long) Product quantity
                                        "BRL")                    // (String) Currency code
                                .build()
                );
            } else if (purchase.getSku().equals(SKU_DONATOR_SUB)) {
			    mDonator = true;
                mConfig.setmDonor(mDonator);
                findViewById(R.id.adFragment).setVisibility(View.GONE);
				
                // May return null if EasyTracker has not yet been initialized with a
                // property ID.
                EasyTracker easyTracker = EasyTracker.getInstance(getApplicationContext());
                easyTracker.send(MapBuilder
                                .createItem(purchase.getToken(),               // (String) Transaction ID
                                        purchase.getItemType(),      // (String) Product name
                                        purchase.getSku(),                  // (String) Product SKU
                                        "Remove Ads",        // (String) Product category
                                        5.00d,                    // (Double) Product price
                                        1L,                       // (Long) Product quantity
                                        "BRL")                    // (String) Currency code
                                .build()
                );
            }
			invalidateOptionsMenu();
        }
    };

    /**
     * This class makes the ad request and loads the ad.
     */
    public static class AdFragment extends Fragment {

        private AdView mAdView;
        private static final String TAG = "AdFragment";

        public AdFragment() {
        }

        @Override
        public void onActivityCreated(Bundle bundle) {
            super.onActivityCreated(bundle);

            // Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
            // values/strings.xml.
            mAdView = (AdView) getView().findViewById(R.id.adView);

            mAdView.setAdListener(new AdListener() {
                @Override
                public void onAdLoaded() {
                    mAdView.setVisibility(View.VISIBLE);
                    Log.d("TAG","onAdLoaded");
                    super.onAdLoaded();
                }

                @Override
                public void onAdClosed() {
                    mAdView.setVisibility(View.GONE);
                    Log.d("TAG","onAdClosed");
                    super.onAdClosed();
                }
            });

            // Create an ad request. Check logcat output for the hashed device ID to
            // get test ads on a physical device. e.g.
            // "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
            AdRequest adRequest = new AdRequest.Builder()
                    .addTestDevice(AdRequest.DEVICE_ID_EMULATOR).addTestDevice("5A9C3E1F678D893049DD767D587A4446")
                    .build();

            // Start loading the ad in the background.
            if(!mRemoverAds) {
                mAdView.loadAd(adRequest);
            }
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_ad, container, true);
        }

        /** Called when leaving the activity */
        @Override
        public void onPause() {
            if (mAdView != null) {
                mAdView.pause();
            }
            super.onPause();
        }

        /** Called when returning to the activity */
        @Override
        public void onResume() {
            super.onResume();
            if (mAdView != null) {
                mAdView.resume();
            }
        }

        /** Called before the activity is destroyed */
        @Override
        public void onDestroy() {
            if (mAdView != null) {
                mAdView.destroy();
            }
            super.onDestroy();
        }

    }
}
